import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateGoodTypeDto } from './dto/create-good-type.dto';
import { UpdateGoodTypeDto } from './dto/update-good-type.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { GoodType } from './entities/good-type.entity';
import { Repository, TreeRepository } from 'typeorm';
import { DeleteIds } from '../dto/all-dto';

@Injectable()
export class GoodTypeService {
  constructor(
    @InjectRepository(GoodType)
    private goodTypeRepository: TreeRepository<GoodType>,
  ) {
  }

  async create(createGoodTypeDto: CreateGoodTypeDto) {
    const { name, parent } = createGoodTypeDto;
    if (
      await this.goodTypeRepository.createQueryBuilder()
        .where('name = :name', { name })
        .getOne()
    ) {
      throw new HttpException('分类已存在', HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return await this.goodTypeRepository.save({ name });
  }

  async findAll() {
    return await this.goodTypeRepository.findRoots();
  }

  findOne(id: number) {
    return `This action returns a #${id} goodType`;
  }

  update(id: number, updateGoodTypeDto: UpdateGoodTypeDto) {
    return `This action updates a #${id} goodType`;
  }

  remove(ids: DeleteIds) {
    return `This action removes a #${ids} goodType`;
  }
}
